class BasePlugin {
    constructor() {
        this.name = '基础插件';
        this.version = '1.0.0';
        this.author = '开发者';
        this.description = '插件描述';
        
        // 新增智能管理字段
        this.priority = 50; // 优先级 1-100，数字越大越先执行
        this.enabled = true; // 插件是否启用
        this.healthStatus = 'unknown'; // healthy, warning, error
        this.commands = new Map(); // 命令注册表
        this.dependencies = []; // 依赖的其他插件
        this.config = {}; // 插件配置
    }

    // ==================== 智能管理方法 ====================
    
    /**
     * 获取插件完整信息
     */
    getInfo() {
        return {
            name: this.name,
            version: this.version,
            author: this.author,
            description: this.description,
            priority: this.priority,
            enabled: this.enabled,
            health: this.healthStatus,
            commands: this.getCommandsInfo(),
            dependencies: this.dependencies,
            config: this.config
        };
    }

    /**
     * 获取命令信息
     */
    getCommandsInfo() {
        return Array.from(this.commands.entries()).map(([command, info]) => ({
            command,
            description: info.description,
            usage: info.usage,
            example: info.example,
            permission: info.permission
        }));
    }

    /**
     * 注册命令
     */
    registerCommand(command, description, usage = '', example = '', permission = 'all') {
        this.commands.set(command, {
            description,
            usage,
            example,
            permission,
            plugin: this.name
        });
        return this;
    }

    /**
     * 插件健康检查
     */
    async healthCheck() {
        try {
            // 检查必要方法
            const requiredMethods = ['onPrivateMessage', 'onGroupMessage'];
            const missingMethods = requiredMethods.filter(method => typeof this[method] !== 'function');
            
            if (missingMethods.length > 0) {
                this.healthStatus = 'error';
                return {
                    healthy: false,
                    errors: [`缺少必要方法: ${missingMethods.join(', ')}`]
                };
            }

            // 检查配置完整性
            const configCheck = await this.checkConfig();
            if (!configCheck.healthy) {
                this.healthStatus = 'warning';
                return configCheck;
            }

            this.healthStatus = 'healthy';
            return { healthy: true };

        } catch (error) {
            this.healthStatus = 'error';
            return {
                healthy: false,
                errors: [`健康检查异常: ${error.message}`]
            };
        }
    }

    /**
     * 检查配置完整性（子类可重写）
     */
    async checkConfig() {
        return { healthy: true };
    }

    /**
     * 设置配置
     */
    setConfig(config) {
        this.config = { ...this.config, ...config };
        return this;
    }

    /**
     * 添加依赖
     */
    addDependency(pluginName) {
        if (!this.dependencies.includes(pluginName)) {
            this.dependencies.push(pluginName);
        }
        return this;
    }

    // ==================== 增强的事件处理方法 ====================
    
    /**
     * 私聊消息 - 增强返回
     */
    onPrivateMessage(event, reply) {
        return { 
            handled: false,
            continuePropagation: true // 是否继续传递给其他插件
        };
    }

    /**
     * 群聊消息 - 增强返回
     */
    onGroupMessage(event, reply) {
        return { 
            handled: false,
            continuePropagation: true
        };
    }

    /**
     * 消息发送（自己发送的消息）
     */
    onMessageSent(event, reply) {
        return { handled: false };
    }

    // ==================== 通知事件 ====================
    
    onGroupUpload(event, reply) {
        return { handled: false };
    }

    onGroupAdminChange(event, reply) {
        return { handled: false };
    }

    onGroupMemberDecrease(event, reply) {
        return { handled: false };
    }

    onGroupMemberIncrease(event, reply) {
        return { handled: false };
    }

    onGroupBan(event, reply) {
        return { handled: false };
    }

    onFriendAdd(event, reply) {
        return { handled: false };
    }

    onGroupRecall(event, reply) {
        return { handled: false };
    }

    onFriendRecall(event, reply) {
        return { handled: false };
    }

    onGroupCardChange(event, reply) {
        return { handled: false };
    }

    onOfflineFile(event, reply) {
        return { handled: false };
    }

    onClientStatusChange(event, reply) {
        return { handled: false };
    }

    onEssenceMessageChange(event, reply) {
        return { handled: false };
    }

    onNotify(event, reply) {
        return { handled: false };
    }

    onGroupTitleChange(event, reply) {
        return { handled: false };
    }

    onGroupLuckyKing(event, reply) {
        return { handled: false };
    }

    onGroupHonorChange(event, reply) {
        return { handled: false };
    }

    // ==================== 请求事件 ====================
    
    onFriendRequest(event, approve) {
        return { handled: false };
    }

    onGroupRequest(event, approve) {
        return { handled: false };
    }

    // ==================== 元事件 ====================
    
    onLifecycle(event, reply) {
        return { handled: false };
    }

    onHeartbeat(event, reply) {
        return { handled: false };
    }

    // ==================== 生命周期方法 ====================
    
    async onInit() {
        // 默认健康检查
        await this.healthCheck();
    }

    async onDestroy() {
        // 清理资源
    }

    /**
     * 重新加载配置
     */
    async reloadConfig(newConfig) {
        this.config = { ...this.config, ...newConfig };
        await this.healthCheck();
    }

    // ==================== 增强的工具方法 ====================
    
    /**
     * 检查消息是否匹配命令
     */
    matchCommand(message, command) {
        if (!message || !command) return false;
        const trimmed = message.trim();
        return trimmed === command || trimmed.startsWith(command + ' ');
    }

    /**
     * 解析命令和参数
     */
    parseCommand(message, command) {
        if (!this.matchCommand(message, command)) return null;
        
        const parts = message.trim().split(' ').filter(Boolean);
        return {
            command: parts[0],
            args: parts.slice(1),
            raw: message
        };
    }

    /**
     * 检查消息是否包含关键词
     */
    hasKeyword(message, keywords) {
        if (!message || !keywords) return false;
        
        if (Array.isArray(keywords)) {
            return keywords.some(keyword => message.includes(keyword));
        }
        return message.includes(keywords);
    }

    /**
     * 检查是否@了机器人
     */
    isAtBot(message, selfId) {
        if (!message) return false;
        return message.includes('[CQ:at,qq=self]') || 
               (selfId && message.includes(`[CQ:at,qq=${selfId}]`));
    }

    /**
     * 提取纯文本（去除CQ码）
     */
    getPlainText(message) {
        if (!message) return '';
        return message.replace(/\[CQ:[^\]]+\]/g, '').trim();
    }

    /**
     * 延迟函数
     */
    sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    /**
     * 获取CQ码参数
     */
    getCQParams(message, cqType) {
        const regex = new RegExp(`\\[CQ:${cqType},([^\\]]+)\\]`, 'g');
        const matches = [];
        let match;
        
        while ((match = regex.exec(message)) !== null) {
            const params = {};
            match[1].split(',').forEach(pair => {
                const [key, value] = pair.split('=');
                if (key && value) params[key] = value;
            });
            matches.push(params);
        }
        
        return matches;
    }

    /**
     * 安全执行函数（带错误处理）
     */
    async safeExecute(fn, context = {}) {
        try {
            return await fn();
        } catch (error) {
            console.error(`[${this.name}] 执行错误:`, error);
            return { error: error.message, success: false };
        }
    }

    /**
     * 记录插件日志
     */
    log(level, message, data = {}) {
        const timestamp = new Date().toISOString();
        console.log(`[${timestamp}] [${this.name}] [${level.toUpperCase()}] ${message}`, data);
    }

    /**
     * 检查权限
     */
    checkPermission(userId, requiredPermission) {
        // 基础权限检查，子类可重写
        const permissions = {
            'all': () => true,
            'admin': (userId) => this.isAdmin(userId),
            'owner': (userId) => this.isOwner(userId)
        };
        
        const checkFn = permissions[requiredPermission] || permissions['all'];
        return checkFn(userId);
    }

    /**
     * 检查是否是管理员（需要子类实现）
     */
    isAdmin(userId) {
        // 需要根据实际业务实现
        return false;
    }

    /**
     * 检查是否是群主（需要子类实现）
     */
    isOwner(userId) {
        // 需要根据实际业务实现
        return false;
    }
}

module.exports = BasePlugin;